package com.brush.pig.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.common.constant.CacheConstants;
import com.brush.common.exception.database.PrimaryKeyException;
import com.brush.common.exception.database.RecordNotFoundException;
import com.brush.common.utils.SecurityUtils;
import com.brush.pig.domain.IotDormSterilize;
import com.brush.pig.domain.req.safety.IotDormSterilizeAddReq;
import com.brush.pig.domain.req.safety.IotDormSterilizeReq;
import com.brush.pig.domain.resp.safety.IotDormSterilrzeResp;
import com.brush.pig.service.IotDormSterilizeService;
import com.brush.pig.mapper.IotDormSterilizeMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
* @author ckq
* @description 针对表【iot_dorm_sterilize(圈舍消毒)】的数据库操作Service实现
* @createDate 2024-11-13 09:03:42
*/
@Service
public class IotDormSterilizeServiceImpl extends ServiceImpl<IotDormSterilizeMapper, IotDormSterilize>
    implements IotDormSterilizeService{

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public PageInfo<IotDormSterilrzeResp> pagination(IotDormSterilizeReq req) {
        return PageHelper.startPage(req.getPageNum(),req.getPageSize()).doSelectPageInfo(()->{
            this.baseMapper.pagination(req);
        });
    }

    @Override
    public boolean add(IotDormSterilizeAddReq req) {
        IotDormSterilize iotDormSterilize = new IotDormSterilize();
        BeanUtils.copyProperties(req,iotDormSterilize);

        iotDormSterilize.setCreatedBy(SecurityUtils.getUserId());
        iotDormSterilize.setUpdatedBy(SecurityUtils.getUserId());
        iotDormSterilize.setCreatedTime(new Date());

        boolean result = this.save(iotDormSterilize);

        if(result){
            //清除redis缓存
            redisTemplate.opsForValue().set(CacheConstants.STERILIZE_KEY+iotDormSterilize.getType(),iotDormSterilize);

        }

        return result;

    }

    @Override
    public IotDormSterilrzeResp findById(Long id) {
        //验证主键是否存在
        if(Objects.isNull(id)){
            throw new PrimaryKeyException();
        }
        //根据id查询消毒的详情
        IotDormSterilize db = this.getById(id);
        //数据库找不到数据
        if(Objects.isNull(db)){
            throw new RecordNotFoundException();
        }
        //封装成返回对象
        IotDormSterilrzeResp resp = new IotDormSterilrzeResp();
        BeanUtils.copyProperties(db,resp);

        return resp;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Long[] ids) {
        if(Objects.isNull(ids) || ids.length==0){
            throw new PrimaryKeyException();
        }

        final IotDormSterilizeServiceImpl iotDormSterilizeService = this;
        this.redisTemplate.execute(new SessionCallback<Void>() {

            @Override
            public Void execute(RedisOperations operations) throws DataAccessException {
                //开启redis事务
                operations.multi();
                //循环删除数据库，时间复杂度：O(n)，事务问题
                try{
                    for (Long id : ids) {
                        IotDormSterilize db = iotDormSterilizeService.getById(id);
                        //数据库找到数据
                        if(Objects.nonNull(db)){
                            //删除数据库中的值
                            iotDormSterilizeService.removeById(id);
                            //移除缓存中的值
                            String redisKey = CacheConstants.STERILIZE_KEY+db.getType();
                            operations.delete(redisKey);
                        }
                     }
                    // 提交redis事务
                    operations.exec();
                }catch(Exception e){
                    // 回滚redis事务
                    operations.discard();
                    throw e;
                }
                return null;
            }

        });
        return true;
    }
}




